package models

type InOrder struct {
	Model
	Type        int             `json:"type"`
	OrderStatus int             `json:"order_status"`
	Code        string          `json:"code"`
	TotalPrice  float64         `json:"total_price"`
	TotalNum    int             `json:"total_num"`
	CreateUser  string          `json:"create_user"`
	StorageId   int             `json:"storage_id"`
	StorageName string          `json:"storage_name"`
	Remark      string          `json:"remark"`
	Status      int             `json:"status"`
	OrderDetail []InOrderDetail `json:"order_detail"`
}

func AddInOrder(data map[string]interface{}) (id int) {
	res := db.Create(&InOrder{
		StorageId:   data["storage_id"].(int),
		StorageName: data["storage_name"].(string),
		Type:        data["type"].(int),
		Code:        data["code"].(string),
		TotalPrice:  data["total_price"].(float64),
		TotalNum:    data["total_num"].(int),
		CreateUser:  data["create_user"].(string),
		Remark:      data["remark"].(string),
	})

	return res.Value.(*InOrder).ID
}

func ExistInOrderById(id int) bool {
	var inOrder InOrder
	db.Model(&inOrder).Where("id=?", id).First(&inOrder)
	if inOrder.ID > 0 {
		return true
	}
	return false
}

func DeleteInOrder(id int) bool {
	err := db.Model(&InOrder{}).Where("id=?", id).Update("status", 0).Error
	if err != nil {
		return false
	}
	return true
}

/**
审批通过
*/
func EditInOrder(id int, data map[string]interface{}) bool {
	db.Model(&InOrder{}).Where("id=?", id).Update(&InOrder{
		OrderStatus: 2,
		TotalPrice:  data["total_price"].(float64),
		TotalNum:    data["total_num"].(int),
		Remark:      data["remark"].(string),
	})

	inorder, _ := GetOrderById(id)
	for _, v := range inorder.OrderDetail {
		IncrementStockNum(inorder.StorageId, v.ProductId, v.Num)
	}

	return true
}

func GetOrderById(id int) (*InOrder, error) {
	var inOrder InOrder
	err := db.Where("id=? and status=?", id, 1).First(&inOrder).Error
	if err != nil {
		return nil, err
	}

	err = db.Model(&inOrder).Related(&inOrder.OrderDetail).Error
	if err != nil {
		return nil, err
	}

	return &inOrder, nil
}

func GetInOrderList(pageNum int, pageSize int, maps interface{}) ([]*InOrder, error) {
	var inOrders []*InOrder
	err := db.Where(maps).Where("status=?", 1).Offset(pageNum).Limit(pageSize).Find(&inOrders).Error
	if err != nil {
		return nil, err
	}

	return inOrders, nil
}

func GetInOrderTotal(maps interface{}) (int, error) {
	var count int
	err := db.Model(&InOrder{}).Where("status=?", 1).Where(maps).Count(&count).Error
	if err != nil {
		return 0, err
	}
	return count, nil
}
